#include <iostream>
#include <cstdlib>
#include <iomanip>

#include "hunterAPI.hpp"
#include "hunterHTTP.hpp"
using namespace std;

int main()
{
	HunterAPI::HiveMind hm("./database");
	freopen("./log", "w+", stderr);
	
	// login user
	string form_o, err;
	int id;
	getline(cin, form_o);
	if (hm.loginPlayer(form_o, err, id))
	{
		cout << "Content-type: text/html\n\n";
		o_header("Login failed");
		o_login_error(err);
		o_footer();
		return 0;
	}
	
	HunterAPI::Player pl;
	if (hm.getPlayerById(id, pl))
	{
		cout << "Content-type: text/html\n\n";
		o_header("Fail");
		o_internal_error("getPlayerById error");
		o_footer();
		return 0;
	}
	
	// login OK, sending cookie
	string cookie = HunterAPI::getNewCode() + HunterAPI::getNewCode() + HunterAPI::getNewCode() + HunterAPI::getNewCode();
	if (hm.bakeCookie(id, cookie))
	{
		cout << "Content-type: text/html\n\n";
		o_header("Fail");
		o_internal_error("Cookie error: ");
		o_footer();
		return 0;
	}
	cout << "Set-Cookie: name=" << cookie << ";\n";

	// redirect to blog
	cout << "Content-type: text/html\n\n";
	
	o_header("OK");
	cout << "<form id = 'fly' method = 'post' action = '" << path_home << "/cgi-bin/blog.cgi'></form>";
	cout << "<script>";
	cout << "document.getElementById(\"fly\").submit();";
	cout << "</script>";
	o_footer();
	
	return 0;
}
